package Thread;
import java.util.Arrays;
import java.util.Comparator;
/**设置锁排序*/

public class demo20_4 {
    public static void main(String[] args) {
        int n = 5; // 线程数量
        int m = 5; // 锁的数量

        Object[] locks = new Object[m];
        for (int i = 0; i < m; i++) {
            locks[i] = new Object();
        }

        for (int i = 0; i < n; i++) {
            final int threadIndex = i;
            Thread t = new Thread(() -> {
                Object[] sortedLocks = Arrays.copyOf(locks, locks.length);
                Arrays.sort(sortedLocks, Comparator.comparing(System::identityHashCode)); // 按照锁的哈希码排序

                for (Object lock : sortedLocks) {
                    synchronized (lock) {
                        System.out.println("线程 " + threadIndex + " 获取锁 " + System.identityHashCode(lock));
                        try {
                            Thread.sleep(1000); // 模拟耗时操作
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            });
            t.start();
        }
    }
}